<?php

/**
* This is the model class for table "tbl_post".
*
* The followings are the available columns in table 'tbl_post':
* @property integer $id
* @property string $title
* @property string $content
* @property string $tags
* @property integer $status
* @property string $create_time
* @property string $update_time
* @property integer $author_id
*/
class Post extends CActiveRecord
{
    const STATUS_DRAFT=1;
    const STATUS_PUBLISHED=2;
    const STATUS_ARCHIVED=3;
    
    public $author_name;

    private $_oldTags;  
    /**
    * Returns the static model of the specified AR class.
    * @return Post the static model class
    */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
    * @return string the associated database table name
    */
    public function tableName()
    {
        return 'tbl_post';
    }

    /**
    * @return array validation rules for model attributes.
    */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
        array('title, content, status', 'required'),
        array('status', 'in', 'range'=>array(1,2,3)),
        array('title' , 'length', 'max'=>128),
        array('tags', 'match', 'pattern'=>'/^[\w\s,]+$/', 'message'=>'Tags can only contain word characters.'),
        array('tags', 'normalizeTags'),
        array('id,author_name, title, status', 'safe', 'on'=>'search'),


        );  

    }
    /**
    * Install Behaviors AutoTimestamp
    */
    public function behaviors(){
        return array(
        'AutoTimestampBehavior' => array(
        'class' => 'application.behaviors.AutoTimestampBehavior',
        //You can optionally set the field name options here
        )
        );
    }

    public function normalizeTags($attribute,$params)
    {
        $this->tags=Tag::array2string(array_unique(Tag::string2array($this->tags)));        
    }

    //Add comment
    public function addComment($comment)
    {    
        $comment->status=2;
        $comment->post_id=$this->id;
        return $comment->save();
    }

    /**
    * @return array relational rules.
    */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        'author' => array(self::BELONGS_TO, 'User', 'author_id'),
        'comments' => array(self::HAS_MANY, 'Comment', 'post_id',
        'condition'=>'comments.status='.Comment::STATUS_APPROVED,
        'order'=>'comments.create_time '),
        'commentCount' => array(self::STAT, 'Comment', 'post_id',
        'condition'=>'status='.Comment::STATUS_APPROVED),
        );
    }


    /**
    * @return array customized attribute labels (name=>label)
    */
    public function attributeLabels()
    {
        return array(
        'id' => 'ID',
        'title' => Yii::t('Site','TITLE'), 
        'alias' => Yii::t('Site','ALIAS'), 
        'content' => Yii::t('Site','CONTENT'), 
        'tags' => Yii::t('Site','TAG'), 
        'status' => Yii::t('Site','STATUS'), 
        'create_time' => Yii::t('Site','CREATE DATE'), 
        'update_time' => Yii::t('Site','UPDATE TIME'), 
        'author_id' => Yii::t('Site','AUTHOR'), 
        'image' => Yii::t('Site','IMAGE'), 
        );
    }

    /**
    * Get url of the post.     
    */
    public function getUrl()
    {
        return Yii::app()->urlManager->createUrl('post/view', array(               
        'alias'=>$this->alias,
        ));

    }
    /**
    * Retrieves a list of models based on the current search/filter conditions.
    * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
    */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;        


        $criteria->compare('id',$this->id);
        $criteria->compare('title',$this->title,true);
        $criteria->compare('alias',$this->alias,true);
        $criteria->compare('content',$this->content,true);
        $criteria->compare('tags',$this->tags,true);
        $criteria->compare('status',$this->status);
        $criteria->compare('create_time',$this->create_time,true);
        $criteria->compare('update_time',$this->update_time,true);
        //Join Author 
        $criteria->with="author";
        //If using compare
        //$criteria->compare('author.username',$this->author_id,true,'LIKE');        
        $criteria->addCondition('author.username LIKE "%'.$this->author_name.'%"');
        return new CActiveDataProvider(get_class($this), array(
        'criteria'=>$criteria,
        ));      
    }
    protected function beforeSave()
    {
        if(parent::beforeSave())
        {
            if($this->isNewRecord)
            {
                $this->author_id=Yii::app()->user->id;            
            }
            //$this->update_time=date('Y-m-d',time());
            return true;
        }
        else
            return false;
    }
    protected function afterSave()
    {
        parent::afterSave();

        Tag::model()->updateFrequency($this->_oldTags, $this->tags);
    }
    protected function afterDelete()
    {
        parent::afterDelete();
        Comment::model()->deleteAll('post_id='.$this->id);
        Tag::model()->updateFrequency($this->tags, '');
    }


    protected function afterFind()
    {
        parent::afterFind();
        $this->_oldTags=$this->tags;
    }

    public function getStatusOptions($i=0)
    {
        $a= array(
        self::STATUS_DRAFT=>'Draft',
        self::STATUS_PUBLISHED=>'Published',
        self::STATUS_ARCHIVED=>'Archived',
        );
        return $i ? $a[$i]:$a;
    }   


    public function getTagLinks()
    {
        $links=array();
        foreach(Tag::string2array($this->tags) as $tag)
            $links[]=CHtml::link(CHtml::encode($tag), array('post/index', 'tag'=>$tag));
        return $links;
    }

    /**    
    * $string is a string that you need replace
    * @return a alias (exmple: chao-cac-ban)
    */
    public function stringURLSafe($string)
    {
        $trans = array(
        "đ"=>"d","ă"=>"a","â"=>"a","á"=>"a","à"=>"a",
        "ả"=>"a","ã"=>"a","ạ"=>"a",
        "ấ"=>"a","ầ"=>"a","ẩ"=>"a","ẫ"=>"a","ậ"=>"a",
        "ắ"=>"a","ằ"=>"a","ẳ"=>"a","ẵ"=>"a","ặ"=>"a",
        "é"=>"e","è"=>"e","ẻ"=>"e","ẽ"=>"e","ẹ"=>"e",
        "ế"=>"e","ề"=>"e","ể"=>"e","ễ"=>"e","ệ"=>"e",
        "í"=>"i","ì"=>"i","ỉ"=>"i","ĩ"=>"i","ị"=>"i",
        "ư"=>"u","ô"=>"o","ơ"=>"o","ê"=>"e",
        "Ư"=>"u","Ô"=>"o","Ơ"=>"o","Ê"=>"e",
        "ú"=>"u","ù"=>"u","ủ"=>"u","ũ"=>"u","ụ"=>"u",
        "ứ"=>"u","ừ"=>"u","ử"=>"u","ữ"=>"u","ự"=>"u",
        "ó"=>"o","ò"=>"o","ỏ"=>"o","õ"=>"o","ọ"=>"o",
        "ớ"=>"o","ờ"=>"o","ở"=>"o","ỡ"=>"o","ợ"=>"o",
        "ố"=>"o","ồ"=>"o","ổ"=>"o","ỗ"=>"o","ộ"=>"o",
        "ú"=>"u","ù"=>"u","ủ"=>"u","ũ"=>"u","ụ"=>"u",
        "ứ"=>"u","ừ"=>"u","ử"=>"u","ữ"=>"u","ự"=>"u",
        "ý"=>"y","ỳ"=>"y","ỷ"=>"y","ỹ"=>"y","ỵ"=>"y",
        "Ý"=>"Y","Ỳ"=>"Y","Ỷ"=>"Y","Ỹ"=>"Y","Ỵ"=>"Y",
        "Đ"=>"D","Ă"=>"A","Â"=>"A","Á"=>"A","À"=>"A",
        "Ả"=>"A","Ã"=>"A","Ạ"=>"A",
        "Ấ"=>"A","Ầ"=>"A","Ẩ"=>"A","Ẫ"=>"A","Ậ"=>"A",
        "Ắ"=>"A","Ằ"=>"A","Ẳ"=>"A","Ẵ"=>"A","Ặ"=>"A",
        "É"=>"E","È"=>"E","Ẻ"=>"E","Ẽ"=>"E","Ẹ"=>"E",
        "Ế"=>"E","Ề"=>"E","Ể"=>"E","Ễ"=>"E","Ệ"=>"E",
        "Í"=>"I","Ì"=>"I","Ỉ"=>"I","Ĩ"=>"I","Ị"=>"I",
        "Ư"=>"U","Ô"=>"O","Ơ"=>"O","Ê"=>"E",
        "Ư"=>"U","Ô"=>"O","Ơ"=>"O","Ê"=>"E",
        "Ú"=>"U","Ù"=>"U","Ủ"=>"U","Ũ"=>"U","Ụ"=>"U",
        "Ứ"=>"U","Ừ"=>"U","Ử"=>"U","Ữ"=>"U","Ự"=>"U",
        "Ó"=>"O","Ò"=>"O","Ỏ"=>"O","Õ"=>"O","Ọ"=>"O",
        "Ớ"=>"O","Ờ"=>"O","Ở"=>"O","Ỡ"=>"O","Ợ"=>"O",
        "Ố"=>"O","Ồ"=>"O","Ổ"=>"O","Ỗ"=>"O","Ộ"=>"O",
        "Ú"=>"U","Ù"=>"U","Ủ"=>"U","Ũ"=>"U","Ụ"=>"U",
        "Ứ"=>"U","Ừ"=>"U","Ử"=>"U","Ữ"=>"U","Ự"=>"U",);
        //remove any '-' from the string they will be used as concatonater
        $str = str_replace('-', ' ', $string);
        $str = strtr($str, $trans);
        // remove any duplicate whitespace, and ensure all characters are alphanumeric
        $str = preg_replace(array('/\s+/','/[^A-Za-z0-9\-]/'), array('-',''), $str);
        // lowercase and trim
        $str = trim(strtolower($str));
        return $str;
    }


    /**
    * Function check exist alias of post
    * It return an unique alias.
    */
    public function CheckExistAlias($alias,$id)
    {
        if($id==0)
        {
            $PostNumber=Post::model()->count('alias=:alias',array(':alias'=>$alias));
        }
        else
        {
            $PostNumber=Post::model()->count('alias=:alias AND id!=:id',array(':alias'=>$alias,':id'=>$id));    
        }

        if($PostNumber>0)
        {
            $alias.='-'.$id;
        }
        return $alias;
    }

    /**     
    * $content is string that is the content of Post
    * $count is the number word that you want get
    * @return Introduce of the Post
    */
    public function getIntroducePost($content,$count)
    {

        $result='';
        $arr=explode(' ',strip_tags($content));
        for($i=0;$i<$count;$i++)
        {
            $result.=$arr[$i]." ";
        }
        return $result.'...';
    }
}
